package com.lkx.farmershop.controller;


import com.lkx.farmershop.common.AiOSS.AliOssUtil;
import com.lkx.farmershop.common.api.ApiResult;
import com.lkx.farmershop.common.context.BaseContext;
import com.lkx.farmershop.service.IFarmerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private IFarmerService farmerService;

    @PostMapping("/upload")
    public ApiResult<String> upload(MultipartFile file){
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名后缀 .jpg
            String fileName= UUID.randomUUID().toString() +originalFilename.substring(originalFilename.lastIndexOf("."));

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
            return ApiResult.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return ApiResult.failed("上传失败");
    }

    @PostMapping("/changeAvatar")
    public ApiResult<String> changeAvatar(MultipartFile file){
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名后缀 .jpg
            String fileName= UUID.randomUUID().toString() +originalFilename.substring(originalFilename.lastIndexOf("."));

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);

            //数据库更改用户头像
            Long userId = BaseContext.getCurrentId();
            farmerService.update().set("avatar",filePath).eq("id",userId).update();

            return ApiResult.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return ApiResult.failed("上传失败");
    }
}
